<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>部门信息</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addDeptDialog">新增部门</el-button>
        </el-col>
      </el-row>

      <!-- 2.2定义表格数据-->
      <el-table :data="departmentList" style="width: 100%;margin-bottom: 20px;" row-key="depId" border stripe
                lazy :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="depName" label="部门名称"></el-table-column>
        <el-table-column prop="depManager" label="部门主管"></el-table-column>
        <el-table-column prop="depLevel" label="等级">
          <!-- 定义作用域插槽 定义标签等级-->
          <template slot-scope="scope">
            <el-tag effect="dark" type="success" v-if="scope.row.depLevel === 1">一级部门</el-tag>
            <el-tag effect="dark" type="primary" v-if="scope.row.depLevel === 2">二级部门</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="updateDeptBtn(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteDeptBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="新增部门" :visible.sync="addDeptDialogVisible" width="30%" @close="closeAddDeptDialog" center>
      <el-form :model="addDeptForm" :rules="rules" ref="addDeptFormRef" label-width="100px">
        <el-form-item label="部门名称:" prop="depName">
          <el-input v-model="addDeptForm.depName"></el-input>
        </el-form-item>
        <el-form-item label="部门主管:">
          <el-autocomplete popper-class="my-autocomplete" v-model="addDeptForm.depManager"
                           :fetch-suggestions="querySearch"
                           placeholder="请输入内容" @select="handleSelect">
            <i class="el-icon-edit el-input__icon" slot="suffix"></i>
            <template slot-scope="{ item }">
              <div class="name">{{ item.empName }}</div>
              <span class="addr">员工编号:&nbsp;   {{ item.empId }}</span>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="addDeptForm.parentId" @focus="getDepList()">
            <el-option v-for="item in depList" :key="item.id" :label="item.depName" :value="item.depId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDeptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDeptFormBtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改部门信息" :visible.sync="updateDeptDialogVisible" @close="closeUpdateDeptDialog" width="50%">
      <el-form :model="updateDeptForm" :rules="rules" ref="updateDeptCatForm" label-width="100px">
        <el-form-item label="部门名称:" prop="depName">
          <el-input v-model="updateDeptForm.depName" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门主管">
          <el-select v-model="updateDeptForm.depManager" placeholder="请选择" @change="changeDepManager">
            <el-option v-for="item in empList" :key="item.id" :label="item.empName" :value="item.empId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDeptDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateDeptInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.findDepartmentList()
    this.loadAll()
  },
  data() {
    return {
      departmentList: [],
      addItemCatDialogVisible: false,
      updateDeptDialogVisible: false,
      addDeptDialogVisible: false,
      addDeptForm: {
        depName: '',
        depManager: '',
        managerId: '',
        parentId: '',
      },
      updateDeptForm: {
        depId: '',
        depName: '',
        managerId: '',
        depManager: ''
      },
      empList: [],
      restaurants: [],
      depList: [],
      rules: {
        deptName: [{required: true, message: '请输入部门名称', trigger: 'blur'}]
      },
    }
  },
  methods: {
    //获取部门列表
    async findDepartmentList() {
      const {data: res} = await this.$http.get("/admin/dept/getDeptList/2").catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error("查询部门信息失败")
      this.departmentList = res.data
    },

    //新增部门
    addDeptDialog() {
      this.addDeptDialogVisible = true
    },
    closeAddDeptDialog() {
      this.$refs.addDeptFormRef.resetFields()
    },
    async addDeptFormBtn() {
      const {data: res} = await this.$http.post("/admin/dept/addNewDept",
        this.addDeptForm).catch(function (e) {
        alert(e)
      })
      if (res.status !== 200) return this.$message.error(res.data)
      this.$message.success(res.data)
      this.addDeptDialogVisible = false
      await this.findDepartmentList()
      this.addDeptForm = {}
    },

    async getDepList() {
      const {data: res} = await this.$http.get("/admin/dept/getDeptList/1").catch(
        function (e) {
          return this.$message.error(e)
        });
      this.depList = res.data
    },

    querySearch(queryString, cb) {
      const restaurants = this.restaurants;
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.empName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    async loadAll() {
      const {data: res} = await this.$http.get('/admin/dept/getEmpList').catch(function (e) {
        if (e.response.status === 500) {
          return this.$message.error("服务器错误")
        } else if (e.response.status === 404) {
          return this.$message.error("页面不存在")
        } else {
          return this.$message.error(e)
        }
      })
      if (res.status !== 200) return this.$message.error("查询失败")
      this.restaurants = res.data
    },
    handleSelect(item) {
      this.addDeptForm.depManager = item.empName
      this.addDeptForm.managerId = item.empId
    },

    async getEmpList() {
      const {data: res} = await this.$http.get('/admin/dept/getEmpList').catch(function (e) {
        if (e.response.status === 500) {
          return this.$message.error("服务器错误")
        } else if (e.response.status === 404) {
          return this.$message.error("页面不存在")
        } else {
          return this.$message.error(e)
        }
      })
      if (res.status !== 200) return this.$message.error("查询失败")
      this.empList = res.data
    },

    changeDepManager() {
      this.updateDeptForm.managerId = this.updateDeptForm.depManager
    },

    //修改部门信息
    async updateDeptBtn(dept) {
      const {data: res} = await this.$http.get(`/admin/dept/getDeptInfo/${dept.depId}`).catch(function (e) {
        if (e.response.status === 500) {
          return this.$message.error("服务器错误")
        } else if (e.response.status === 404) {
          return this.$message.error("页面不存在")
        } else {
          return this.$message.error(e)
        }
      })
      await this.getEmpList();
      if (res.status !== 200) return this.$message.error("查询失败")
      this.updateDeptForm.depName = res.data.depName
      this.updateDeptForm.depManager = res.data.depManager
      this.updateDeptForm.depId = res.data.depId
      this.updateDeptDialogVisible = true
    },
    closeUpdateDeptDialog() {
      this.$refs.updateDeptCatForm.resetFields()
    },
    async updateDeptInfo() {
      this.updateDeptForm.depManager = ''
      const {data: res} = await this.$http.put("/admin/dept/updateDeptInfo",
        this.updateDeptForm).catch(function (e) {
        return this.$message.error(e)
      })
      if (res.status !== 200) return this.$message.error("更新失败")
      this.$message.success("更新成功")
      await this.findDepartmentList();
      this.updateDeptDialogVisible = false
    },

    //删除部门
    async deleteDeptBtn(dept) {
      console.log(dept)
      const result = await this.$confirm('此操作将永久删除部门 ' + dept.depName + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      //如果确认  confirm  如果取消 cancel
      if (result !== 'confirm') {
        return this.$message.info("删除取消")
      }
      const {data: res} = await this.$http.delete(`/admin/dept/deleteDept/${dept.depId}`).catch(function (e) {
        alert(e)
      })
      if (res.status !== 200) return this.$message.error(res.data)
      await this.findDepartmentList()
      this.$message.success(res.data)
    }
  }
}
</script>

<style scoped lang="less">
.my-autocomplete {

  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }

  }
}

/*定义级联选择器宽度 */
.el-cascader {
  width: 100%;
}
</style>
